<template>
  <div style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">
    <div style="">
      <div style="height:80px;background:white">
        <el-form ref="formQueryRole" label-position="right" label-width="80px" :model="formQueryRole" >
          <el-form-item 
          prop="roleName"
          label="角色名称:" 
          size="mini" 
          style="float:left;display: inline-block;margin-left: 100px;padding-top: 25px;"
          :rules="[
            { required: false, message: '请输入角色名称', trigger: 'blur' }
          ]"
          >
            <el-input v-model="formQueryRole.roleName"></el-input>
          </el-form-item>
          <el-form-item style="float:right;display: inline-block;padding-top: 25px;margin-right: 100px;" >
            <el-button  icon="el-icon-search" size="small" type="success" @click="selectRole()"  >查询</el-button> 
            <el-button icon="el-icon-refresh" @click="resetForm('formQueryRole')" size="small">重置</el-button>
          </el-form-item>
        </el-form>                       
      </div>
      <el-divider></el-divider>
      <div style="height:50px;background:white">
          <el-button size="small" @click="addRoleDialog" icon="el-icon-zoom-in"  type="success"  style="float: left;margin-left: 50px;" >添加角色</el-button>       
      </div>
    </div>
    <el-divider></el-divider>     
    <div>
      <el-table :data="tableData" style="width: 100%"
          @selection-change="handleSelectionChange">
      <el-table-column type="selection" ></el-table-column>
      <el-table-column label="角色名称" align="center">
        <template slot-scope="scope">
          <div>{{ scope.row.roleName }}</div>
        </template>
      </el-table-column>
      <el-table-column label="角色状态" align="center">
        <template slot-scope="scope">
        <el-switch
          v-model="scope.row.states"
          :active-value="1"
          :inactive-value="0"
          active-color="#13ce66"
          inactive-color="#ff4949">
        </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="角色创建时间" align="center">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{$moment(scope.row.createTime).format('YYYY-MM-DD')}}</span>
        </template>
      </el-table-column>      
      <el-table-column label="操作" >
        <template slot-scope="scope">
          <el-button type="text" @click="updateUserDialog(scope.row.roleId)">编辑</el-button>   
          <el-button type="text" :disabled="scope.row.states===0" @click="relationUser(scope.row.roleId)">关联用户</el-button>    
          <el-button type="text" @click="adminDialog(scope.row.roleId)">授权管理</el-button>                                
        </template>
      </el-table-column>
    </el-table>
    </div>
    <div>
      <!--prev表示上一页，next为下一页，pager表示页码列表,total表示总条目数，size用于设置每页显示的页码数量。-->
      <el-pagination
        background
        layout="total,prev,sizes, pager, next,jumper"
        :total="total"
        :page-sizes="[5, 10, 15, 20]"
        :page-size.sync="formSearch.pageSize"
        :current-page.sync="formSearch.pageNum"
        @current-change="getPage"
        @size-change="getPage"
        style="float: right">
      </el-pagination>
    </div>
    <!-- 添加角色 -->
    <div>
      <el-dialog title="添加角色"  :visible.sync="addRoleVisible"  :close-on-click-modal="false" center  >
        <el-divider></el-divider>
        <el-form ref="formAddRole" :model="formAddRole" :rules="formAddRoleRules" center>
          <el-form-item label="角色名称" label-width="140px" prop="roleName">
            <el-input v-model="formAddRole.roleName" placeholder=" 请输入角色名称" ></el-input>
          </el-form-item>       
          <el-form-item label="角色状态" label-width="140px">
            <el-select v-model="formAddRole.states" placeholder="请选择用户状态">
              <el-option label="启用" value="1"></el-option>
              <el-option label="停用" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="addRoleVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="saveRole">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 编辑角色 -->
    <div>
      <el-dialog title="添加角色"  :visible.sync="updateRoleVisible"  :close-on-click-modal="false" center  >
        <el-divider></el-divider>
        <el-form ref="updateRoleData" :model="updateRoleData" :rules="formAddRoleRules" center>
          <el-form-item label="角色名称" label-width="140px" prop="roleName">
            <el-input v-model="updateRoleData.roleName" placeholder=" 请输入角色名称" ></el-input>
          </el-form-item>       
          <el-form-item label="角色状态" label-width="140px">
            <el-select v-model="updateRoleData.states" placeholder="请选择用户状态">
              <el-option label="启用" :value="1"></el-option>
              <el-option label="停用" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="updateRoleVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="updateRole">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 关联用户第一步：查询所有用户 -->
    <div>
      <el-dialog title="关联用户"  :visible.sync="relationUserVisible"  :close-on-click-modal="false" center  >
          <el-table ref="multipleTable" :data="userTableData" style="width: 100%" @selection-change="handleSelectionUserIdChange" @select='selectSingle'>
          <el-table-column type="selection" width="55" :selectable='selectEnable'></el-table-column>
          <el-table-column label="用户名" width="150">
            <template slot-scope="scope">
              <div>{{ scope.row.username }}</div>
            </template>
          </el-table-column>
          <el-table-column label="用户姓名" width="150">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>用户姓名: {{ scope.row.personName }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.personName }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="用户状态" width="150">
            <template slot-scope="scope">
              <!-- <p v-if="scope.row.states===0">可用</p>
              <p v-else>不可用</p> -->
            <el-switch
              v-model="scope.row.states"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="用户创建时间" width="180">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span style="margin-left: 10px">{{$moment(scope.row.createTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>      
          <!-- <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" @click="checkUser(scope.row.userId)">查看</el-button>                            
            </template>
          </el-table-column> -->
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="relationUserVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="addRoleRelationUser">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 授权管理 -->
    <div>
      <el-dialog title="添加权限"  :visible.sync="adminVisible"  :close-on-click-modal="false" center  >
        <div style=" box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);">
          <el-tree
              ref="tree"
              :data="data"
              :show-checkbox="true"
              node-key="menuId"
              :default-expanded-keys="treeExpandData" 
              :expand-on-click-node="false"
              :props="defaultProps"
              :default-checked-keys="checkMenuArray"
              @check-change="checkTree">
              <span class="custom-tree-node show-hide" slot-scope="{ node, data }">
                <span>
                    <i v-if="data.menuType==1" class="el-icon-folder-opened"></i>
                    <i v-else-if="data.menuType==2" class="el-icon-document-remove"></i>
                    <i v-else-if="data.menuType==3" class="el-icon-thumb"></i>
                {{ node.label }}
                </span>
              </span>
          </el-tree>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="cancelAdminVisible">取 消</el-button>
          <el-button size="small" type="primary" @click="addRoleRelationMenu">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import role from '../../api/role'
import user from '../../api/user'
import menu from '../../api/menu'
export default {
  name: "role",
  data(){
    return{
      //渲染数据
      tableData:[],
      total:0,
      //获取所有角色
      formSearch:{
        pageNum:1,
        pageSize:10
      },
      //获取多个id
      roleIdsArray:[],
      roleIds:'',
      //批量获取userId
      userIdsArray:[],
      userIds:'',
      //查询
      formQueryRole:{},
      //根据用户名称查询
      formQueryRole:{
        pageNum:1,
        pageSize:10,
        roleName:''
      },
      //添加角色
      addRoleVisible:false,
      formAddRole:{},
      formAddRoleRules:{
        roleName: [{required:true, message:"请输入账户名称",trigger:'blur'}],
      },
      //修改角色
      updateRoleVisible:false,
      updateRoleData:{},
      //关联用户
      relationUserVisible:false,
      userTableData:[],
      //当前角色关联的用户
      fromQueryRoleRelationUser:{
        roleId:'',
      },
      fromQueryRoleRelationUserData:{},
      //给当前角色添加用户
      fromAddUserData:{
        userIds:'',
        roleId:''
      },
      //授权管理
      adminVisible:false,
      treeExpandData:[119853844214895],
      data: [],
      defaultProps: {
          id:'menuId',
          children: 'children',
          label: 'menuName'
      },
      adminFrom:{
        roleId:''
      },
      //回显菜单信息
      checkMenuFrom:{},
      //默认选中的节点数组
      checkMenuArray:[],

      //角色关联菜单
      fromAddRoleRelationMenuData:{
        roleId:'',
        menuIds:''
      },
    }
  },
  created(){
    this.getPage();
  },
  methods:{
    //多选框选中状态,将roleid转换成一个字符串
    handleSelectionChange(val){
      this.roleIdsArray=val;
      const idList = [];
      for (const v of this.roleIdsArray) {
        idList.push(v.roleId)
      };
      this.roleIds=idList.join(',');
    },
    //多选框选中状态,将roleid转换成一个字符串
    handleSelectionUserIdChange(val){
      this.userIdsArray=val;
      const idList = [];
      for (const v of this.userIdsArray) {
        idList.push(v.userId)
      };
      this.fromAddUserData.userIds=idList.join(',');
    },
    //多选框禁止选中
    selectEnable(row, rowIndex) {
      if (row.states===0) {
        return false
      } else {
        return true// 不禁用
      }
    },
    //多选框选中状态不可取消
    selectSingle(selection,row){
        //默认勾选
        this.$nextTick(()=>{
          try {
            this.fromQueryRoleRelationUserData.forEach((tqrd) =>{
            this.userTableData.forEach((trd)=>{
              if(tqrd.userId == trd.userId){
                this.$refs.multipleTable.toggleRowSelection(trd,true)
              }
            })
          })
          } catch (error) {
            
          }
        });
      },
    //查询所有角色
    async getPage(){
      const res=await role.queryAllRole(this.formSearch);
      if(res.data.code= '000'){
        this.tableData=res.data.data.records;
        this.total=res.data.data.total;
      }
    },
    //根据用户名称模糊查询
    async selectRole(){
      const res=await role.queryAllRole(this.formQueryRole);
      if(res.data.code === '000'){
        this.tableData=res.data.data.records;
        this.total=res.data.data.total;
      }
    },
    //重置模糊查询表单
    resetForm(formQueryRole) {
      this.$refs[formQueryRole].resetFields();
    },
    //添加角色弹窗
    addRoleDialog(){
      this.addRoleVisible=true;
      try {
        this.$refs['formAddRole'].resetFields()
      } catch (err) {

      }
    },
    //添加角色请求
    saveRole(){
      this.$refs.formAddRole.validate((valid) => {
        if (valid) {
          role.saveRole(this.formAddRole).then(res =>{
            if(res.data.code=== '000'){
              this.addRoleVisible=false,
              this.$message.success("添加成功")
              this.getPage();
            }else{
              this.$message.error("添加失败")
            }
          })
        } else {
          return false;
        }
      });
    },
    //修改角色弹窗
    async updateUserDialog(roleId){
      this.updateRoleVisible=true;
      const res=await role.queryRoleByRoleId({roleId:roleId});
      if(res.data.code === '000'){
        this.updateRoleData=res.data.data
      }
    },
    //修改角色请求
    async updateRole(){
      const res=await role.updateRoleByRoleId(this.updateRoleData);
      if(res.data.code === '000'){
        this.updateRoleVisible=false;
        this.$message.success("修改成功");
        this.getPage();
      }else{
        this.$message.error("修改失败")
      }
    },
    //关联用户第一步，查询当前角色所对应的用户
    async getQueryRolePage(){
      const res=await role.queryRoleRelationAllUser(this.fromQueryRoleRelationUser);
      if(res.data.code === '000'){
        this.fromQueryRoleRelationUserData=res.data.data.userList;
      }else{
        this.fromQueryRoleRelationUserData=null
      }
    },
    //关联用户,查询所有用户
    async relationUser(roleId){
      this.relationUserVisible=true;
      this.fromQueryRoleRelationUser.roleId=roleId;
      this.fromAddUserData.roleId=roleId;
      //查询查询当前角色所对应的用户
      this.getQueryRolePage();
      this.queryAllRoleRelationUser();
    },
    async queryAllRoleRelationUser(){
      const res=await user.queryAllUser(this.formSearch);
      if(res.data.code=== '000'){
        this.userTableData=res.data.data.records;
        //默认勾选
        this.$nextTick(()=>{
          try {
            this.fromQueryRoleRelationUserData.forEach((tqrd) =>{
            this.userTableData.forEach((trd)=>{
              if(tqrd.userId == trd.userId){
                this.$refs.multipleTable.toggleRowSelection(trd,true)
              }
            })
          })
          } catch (error) {
            
          }
        });
      }
    },
    //关联用户第二步：给当前角色添加用户
    async addRoleRelationUser(){
      if(this.fromAddUserData.userIds === ''){
        this.$message.error("请选择要添加的用户，不可以取消默认选中");
        this.queryAllRoleRelationUser();
        return false;
      }
      const res=await role.addRoleRelationUser(this.fromAddUserData);
      if(res.data.code === '000'){
        this.$message.success("添加成功");
        this.getQueryRolePage();
      }
    },
    //授权管理
    adminDialog(roleId){

      this.adminFrom.roleId=roleId;
      //角色关联菜单
      this.fromAddRoleRelationMenuData.roleId=roleId;
      this.queryAllMenu();
      this.queryMenuByRole()    
      setTimeout( () =>{
        this.adminVisible=true;
      },500);  
    },
    //添加权限第一步,获取所有菜单
    async queryAllMenu(){
      const res=await menu.queruAllMenu();
      if(res.data.code==='000'){
          this.data=res.data.data
      }
    },
    //添加权限第二步，获取该角色所拥有的的权限
    async queryMenuByRole(){
      const res=await role.queryMenuByRoleId({roleId:this.adminFrom.roleId});
      if(res.data.code==='000'){
          this.checkMenuArray.length=0;
          this.checkMenuFrom=res.data.data
          this.checkMenuFrom.forEach(menu =>{
            if(menu.children.length > 0){
              menu.children.forEach( menus =>{
                if(menus.children.length > 0){
                  menus.children.forEach(men =>{
                    if(men.children.length > 0){
                        men.children.forEach(me =>{
                          // console.log(me+'me');
                          if(me.children.length > 0){
                          }else{
                            this.checkMenuArray.push(me.menuId);
                          }
                        })
                    }else{
                      this.checkMenuArray.push(men.menuId);
                    }
                  })
                }else{
                  this.checkMenuArray.push(menus.menuId);
                }
              })
            }else{
              this.checkMenuArray.push(menu.menuId);
            }
          })
      }else if(res.data.code==='400'){
        this.$message.warning(res.data.msg)
      }
    },
    //递归选择展开的最深节点(待优化项)
    //关闭添加权限弹窗
    cancelAdminVisible(){
      this.adminVisible=false;
      this.$refs.tree.setCheckedKeys([])
    },
    //获取复选框选中的节点id信息
    checkTree(data){
      let arr=this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
      this.fromAddRoleRelationMenuData.menuIds=arr;

    },
    //角色关联菜单第三步，发请求
    async addRoleRelationMenu(){
      const res=await role.addRoleRelationMenu(this.fromAddRoleRelationMenuData);
      if(res.data.code === '000'){
        this.adminVisible=false;
        location.reload();
        this.$message.success("关联成功");
      }
    }
  }
}
</script>

<style scoped>

</style>
